package controller

import (
	"common/config"
	"context"
	"github.com/valyala/fasthttp"
	"math/rand"
	"member/model"
	"strconv"
)

type RedPack struct{}
type RedPackHistory struct {
	amount     float64 //领奖金额
	createAt   int64   //领奖时间
	activityId int     //活动id
}

var G_RedPack RedPack

// 抽红包
func (that *RedPack) Draw(ctx *fasthttp.RequestCtx) {

}

func (that *RedPack) GetActivityBeginTime(ctx *fasthttp.RequestCtx) {

}

func (that *RedPack) randomInRange(min, max int) int {
	if max < min {
		min, max = max, min
	}
	if max-min == 0 {
		max++
	}

	return min + rand.Intn(max-min)
}

/*
红包随机, 领完最后一个刚好红包池空
都用 *1000，的int 来处理

remainingCount 剩余数量
remainingAmount 剩余金额
minAmount 随机最大
maxAmount 随机最小
*/
func (that *RedPack) Allocate(remainingCount, remainingAmount, minAmount, maxAmount int) int {
	if remainingCount <= 0 {
		// 所有红包已经被领取
		return 0
	}

	remainingMin := remainingCount * 10 // 假设最小红包金额是 0.1
	maxAllocatable := remainingAmount - remainingMin
	allocatedAmount := 0

	if maxAllocatable < minAmount {
		if remainingCount == 1 {
			allocatedAmount = remainingAmount
		} else {
			allocatedAmount = that.randomInRange(0, maxAllocatable)
		}
	} else {
		//min
		minval := maxAmount
		if maxAmount > maxAllocatable {
			minval = maxAllocatable
		}

		allocatedAmount = that.randomInRange(minAmount, minval)
	}

	if allocatedAmount < 10 {
		allocatedAmount = 0
	}

	remainingAmount -= allocatedAmount
	remainingCount--

	return allocatedAmount
}

// 抽红包
func (that *RedPack) RedPackDraw() float64 {
	actInfo := config.G_RedPackMgr.GetCurActivity()
	if 0 == actInfo.ActivityId {
		return 0
	}

	strActIdRedis, _ := model.GetRedis().Get(context.Background(), config.RedisActivityId).Result()
	cfgActId, _ := strconv.Atoi(strActIdRedis)
	var amount, count int

	if cfgActId != actInfo.ActivityId {
		//init
		model.GetRedis().Set(context.Background(), config.RedisActivityId, strconv.Itoa(actInfo.ActivityId), 0)
		model.GetRedis().Set(context.Background(), config.RedisRedPackAmount, strconv.Itoa(actInfo.RedPackTotalMoney), 0)
		model.GetRedis().Set(context.Background(), config.RedisRedPackCount, strconv.Itoa(actInfo.RedPackNum), 0)

		amount = actInfo.RedPackTotalMoney * 1000
		count = actInfo.RedPackNum
	} else {
		strAmount, _ := model.GetRedis().Get(context.Background(), config.RedisRedPackAmount).Result()
		strCount, _ := model.GetRedis().Get(context.Background(), config.RedisRedPackCount).Result()
		fAmount, _ := strconv.ParseFloat(strAmount, 64)
		fCount, _ := strconv.ParseFloat(strCount, 64)
		amount = int(fAmount * 1000)
		count = int(fCount)
	}

	redPackMoney := that.Allocate(count, amount, int(actInfo.MoneyMin*1000), int(actInfo.MoneyMax*1000))

	return float64(redPackMoney / 1000)
}
